package com.laowang.common.utils.aip;

import org.apache.commons.io.IOUtils;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * 文件读取工具类
 */
public class FileUtil {

    /**
     * 读取文件内容，作为字符串返回
     */
    public static String readFileAsString(String filePath) throws IOException {
        File file = new File(filePath);
        if (!file.exists()) {
            throw new FileNotFoundException(filePath);
        }

        if (file.length() > 1024 * 1024 * 1024) {
            throw new IOException("File is too large");
        }

        StringBuilder sb = new StringBuilder((int) (file.length()));
        // 创建字节输入流
        FileInputStream fis = new FileInputStream(filePath);
        // 创建一个长度为10240的Buffer
        byte[] bbuf = new byte[10240];
        // 用于保存实际读取的字节数
        int hasRead = 0;
        while ( (hasRead = fis.read(bbuf)) > 0 ) {
            sb.append(new String(bbuf, 0, hasRead));
        }
        fis.close();
        return sb.toString();
    }

    /**
     * 根据文件路径读取byte[] 数组
     */
    public static byte[] readFileByBytes(String filePath) throws IOException {
        //File file = new File(filePath);
        HttpURLConnection httpUrl = (HttpURLConnection) new URL(filePath).openConnection();
        httpUrl.connect();
        InputStream inputStream = httpUrl.getInputStream();
        return IOUtils.toByteArray(inputStream);
    }

    /**
     * 根据文件路径读取byte[] 数组
     */
    public static byte[] readFileByBytes1(String filePath) throws IOException {
        File file = new File(filePath);
        InputStream inputStream =new FileInputStream(file);
        return IOUtils.toByteArray(inputStream);
    }

    public static void main(String[] args) throws IOException {
        byte[] bytes = readFileByBytes("https://mcjlb.cn/images/20230508/ea707ca7e51e4995be2238584b98fdbf.jpg");

    }
}
